package com.czg.jsonschema2lombokpojo.rules;

import java.lang.annotation.Annotation;

import com.czg.jsonschema2lombokpojo.Schema;

import com.fasterxml.jackson.databind.JsonNode;
import com.sun.codemodel.JAnnotationUse;
import com.sun.codemodel.JFieldVar;

import jakarta.validation.constraints.Digits;

public class DigitsRule implements Rule<JFieldVar, JFieldVar> {

    private final RuleFactory ruleFactory;

    protected DigitsRule(RuleFactory ruleFactory) {
        this.ruleFactory = ruleFactory;
    }

    @Override
    public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) {

        if (ruleFactory.getGenerationConfig().isIncludeValidationAnnotations()
            && node.has("integerDigits") && node.has("fractionalDigits")
            && isApplicableType(field)) {

            final Class<? extends Annotation> digitsClass
                    = ruleFactory.getGenerationConfig().isUseJakartaValidation()
                    ? Digits.class
                    : javax.validation.constraints.Digits.class;
            JAnnotationUse annotation = field.annotate(digitsClass);

            annotation.param("integer", node.get("integerDigits").asInt());
            annotation.param("fraction", node.get("fractionalDigits").asInt());
        }

        return field;
    }

    private boolean isApplicableType(JFieldVar field) {
        try {
            Class<?> fieldClass = Class.forName(field.type().boxify().fullName());
            // 支持字符串以及除 Double 和 Float 之外的大多数数字类型，详情请参阅关于 Digits 注解的文档说明。
            return String.class.isAssignableFrom(fieldClass) ||
                    (Number.class.isAssignableFrom(fieldClass) &&
                            !Float.class.isAssignableFrom(fieldClass) && !Double.class.isAssignableFrom(fieldClass));
        } catch (ClassNotFoundException ignore) {
            return false;
        }
    }

}
